package org.groupg.practice.io;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.*;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class CommonsIOExample {
    // 文件夹路径
    private static final String INPUT_DIR = "path/to/input";
    private static final String OUTPUT_DIR = "path/to/output";

    public static void main(String[] args) throws Exception {
        // 监控文件夹变化
        monitorFileChanges();

        // 读取大型文件并处理每一行
        readLargeFile();

        // 复制文件
        copyFile();

        // 移动文件
        moveFile();

        // 写入文件
        writeFile();
    }

    private static void monitorFileChanges() {
        FileAlterationObserver observer = new FileAlterationObserver(INPUT_DIR);
        observer.addListener(new FileAlterationListenerAdaptor() {
            @Override
            public void onFileCreate(File file) {
                System.out.println("New file created: " + file);
            }
        });

        FileAlterationMonitor monitor = new FileAlterationMonitor(1000, observer);
        try {
            monitor.start();
            Runtime.getRuntime().addShutdownHook(new Thread(){
                @Override
                public void run() {
                    try {
                        monitor.stop();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void readLargeFile() throws IOException {
        File largeFile = new File(INPUT_DIR + "/largefile.txt");
        List<String> lines = FileUtils.readLines(largeFile, Charset.defaultCharset());
        lines.forEach(System.out::println);
    }

    private static void copyFile() throws IOException {
        File source = new File(INPUT_DIR + "/source.txt");
        File destination = new File(OUTPUT_DIR + "/destination.txt");
        FileUtils.copyFile(source, destination);
    }

    private static void moveFile() throws IOException {
        File source = new File(OUTPUT_DIR + "/destination.txt");
        File destination = new File(OUTPUT_DIR + "/moved.txt");
        FileUtils.moveFile(source, destination);
    }

    private static void writeFile() throws IOException {
        File destination = new File(OUTPUT_DIR + "/newfile.txt");
        String content = "Hello, World!";
        try (Writer out = new FileWriter(destination)) {
            IOUtils.write(content.getBytes(), out, Charset.defaultCharset());
        }
    }
}